const express = require("express")
const router = express.Router()
const Unit = require("../models/unit")

// 获取楼栋下的所有单元
router.get("/getUnitsByBuilding/:buildingId", async (req, res) => {
  try {
    const units = await Unit.findAll({
      where: { building_id: req.params.buildingId },
      order: [["number", "ASC"]],
    })
    res.json({ code: 200, data: units, message: "获取单元列表成功" })
  } catch (error) {
    res.json({ code: 500, message: "获取单元列表失败" })
  }
})

// 添加单元
router.post("/addUnit", async (req, res) => {
  try {
    const unit = await Unit.create(req.body)
    res.json({ code: 200, data: unit, message: "添加单元成功" })
  } catch (error) {
    res.json({ code: 500, message: "添加单元失败" })
  }
})

// 更新单元
router.put("/updateUnit/:id", async (req, res) => {
  try {
    const unit = await Unit.findByPk(req.params.id)
    if (!unit) return res.json({ code: 404, message: "单元不存在" })
    await unit.update(req.body)
    res.json({ code: 200, message: "更新单元成功" })
  } catch (error) {
    res.json({ code: 500, message: "更新单元失败" })
  }
})

// 删除单元
router.delete("/deleteUnit/:id", async (req, res) => {
  try {
    const unit = await Unit.findByPk(req.params.id)
    if (!unit) return res.json({ code: 404, message: "单元不存在" })
    await unit.destroy()
    res.json({ code: 200, message: "删除单元成功" })
  } catch (error) {
    res.json({ code: 500, message: "删除单元失败" })
  }
})

module.exports = router
